import React from 'react'
import './addGoods.css'
import {Row, Col, Input, Select, Radio, Upload, message, Modal, Table, Button} from 'antd';
import {LoadingOutlined, PlusOutlined} from '@ant-design/icons';


const STATUS_OPTIONS = [{value: '0', label: '促销中'}, {value: '1', label: '仓库中',}, {
    value: '2',
    label: '出售中'
}, {value: '3', label: '已售罄'}];

function getBase64(img, callback) {
    const reader = new FileReader();
    reader.addEventListener('load', () => callback(reader.result));
    reader.readAsDataURL(img);
}

function getImgBase64(file) {
    return new Promise((resolve, reject) => {
        const reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = () => resolve(reader.result);
        reader.onerror = error => reject(error);
    });
}

const columns = [
    {
        title: '商品原价',
        dataIndex: 'yuanjia',
        key: 'yuanjia',
        align: 'center'
    },
    {
        title: '促销价',
        dataIndex: 'cuxiaojia',
        key: 'cuxiaojia',
        align: 'center'
    },
    {
        title: '成本价',
        dataIndex: 'chengbenjia',
        key: 'chengbenjia',
        align: 'center',
        color: 'white'
    },
    {
        title: '快递价',
        dataIndex: 'kuaidijia',
        key: 'kuaidijia',
        align: 'center'
    },
    {
        title: '购买限制（个）',
        dataIndex: 'limitNum',
        key: 'limitNum',
        align: 'center'
    },
    {
        title: '库存',
        dataIndex: 'kucun',
        key: 'kucun',
        align: 'center'
    },
    {
        title: '供货商',
        dataIndex: 'gonghuoshang',
        key: 'gonghuoshang',
        align: 'center'
    },
    {
        title: '供货商电话',
        dataIndex: 'tel',
        key: 'tel',
        align: 'center'
    },
];

function beforeUpload(file) {
    const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
    if (!isJpgOrPng) {
        message.error('You can only upload JPG/PNG file!');
    }
    const isLt2M = file.size / 1024 / 1024 < 2;
    if (!isLt2M) {
        message.error('Image must smaller than 2MB!');
    }
    return isJpgOrPng && isLt2M;
}

class AddGoods extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            goodsName: "",
            radioValue: 1,
            textarea: '',
            loadingOne: false,
            loadingTwo: false,
            imageUrlOne: '',
            imageUrlTwo: '',
            imageUrlThree: '',
            previewVisible: false,
            previewImage: '',
            previewTitle: '',
            fileList: [
                // {uid: '-1', name: 'image.png', status: 'done', url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',},
            ],
            tableData: [{
                key: '1',
                yuanjia: <Input style={{textAlign: 'center'}}/>,
                cuxiaojia: <Input style={{textAlign: 'center'}}/>,
                kuaidijia: <Input style={{textAlign: 'center'}}/>,
                chengbenjia: <Input style={{textAlign: 'center'}}/>,
                limitNum: <Input style={{textAlign: 'center'}}/>,
                kucun: <Input style={{textAlign: 'center'}}/>,
                gonghuoshang: <Input style={{textAlign: 'center'}}/>,
                tel: <Input style={{textAlign: 'center'}}/>,
            },]
        }
        this.handleActivity = this.handleActivity.bind(this)
        this.onChange = this.onChange.bind(this)
        this.handleChange = this.handleChange.bind(this)
    }

    handleCancel = () => this.setState({previewVisible: false});

    handlePreview = async file => {
        if (!file.url && !file.preview) {
            file.preview = await getImgBase64(file.originFileObj);
        }

        this.setState({
            previewImage: file.url || file.preview,
            previewVisible: true,
            previewTitle: file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
        });
    };

    handleMoreChange = ({fileList}) => this.setState({fileList});

    onChange = (e, name) => {
        console.log('radio checked', e.target.value);
        console.log(this.state.goodsName, this.state.radioValue);
        this.setState({
            [name]: e.target.value,
        });
    };

    handleActivity = (e) => {
        // e.preventDefault();
        console.log(e);
    }

    handleChange = id => info => {
        console.log(id, info);


        if (info.file.status === 'done') {
            // Get this url from response in real world.
            switch (id) {
                case 1:
                    getBase64(info.file.originFileObj, imageUrlOne =>
                        this.setState({
                            imageUrlOne,
                            loadingOne: false,
                        }),
                    )

                    break;
                case 2:
                    getBase64(info.file.originFileObj, imageUrlTwo =>
                        this.setState({
                            imageUrlTwo,
                            loadingTwo: false,
                        }),
                    )
                    break;
                default :
                    console.log('default');
                    break;

            }
        }
    };

    render() {
        const uploadButton = (
            <div>
                {this.state.loading ? <LoadingOutlined/> : <PlusOutlined/>}
                <div className="ant-upload-text">Upload</div>
            </div>
        );
        let {goodsName, textarea, imageUrlOne, imageUrlTwo, previewVisible, previewImage, fileList, previewTitle, tableData} = this.state
        return (<div>
            <Row justify='center'>
                <div className='title'>新增商品(零售)</div>
            </Row>
            <Row>
                <div className="title_information">商品基本信息</div>
            </Row>
            <Row style={{marginTop: 20, marginBottom: 20}}>
                <Col span={3} className="text_align_right">
                    <span>商品名称：</span>
                </Col>
                <Col
                    span={6}>
                    <Input id="goodsNameInput"
                           placeholder="请输入名称"
                           value={goodsName}
                           onChange={e => this.onChange(e, 'goodsName')}
                           allowClear>
                    </Input>
                </Col>
                <Col span={3} className="text_align_right" offset={3}>
                    <span>上架状态：</span>
                </Col>
                <Col span={6}>

                    <Select
                        placeholder="请选择"
                        className='selectWith'
                        onChange={e => this.handleActivity(e)}>
                        {STATUS_OPTIONS.map(it => (
                            <Select.Option key={it.value} value={it.value}>
                                {it.label}
                            </Select.Option>
                        ))}
                    </Select>

                </Col>
            </Row>
            <Row>
                <Col span={3} className="text_align_right">
                    <span>商品描述：</span>
                </Col>
                <Col span={6}>
                    <Input.TextArea
                        rows="3"
                        onChange={e => this.onChange(e, 'textarea')}
                        placeholder="请输入内容"
                        value={textarea}>
                    </Input.TextArea>
                </Col>

                <Col span={3} className="text_align_right" offset="3">
                    <span>上架状态：</span>
                </Col>
                <Col span="6">
                    <Radio.Group onChange={e => this.onChange(e, 'radioValue')} value={this.state.radioValue}>
                        <Radio value={1}>线上</Radio>
                        <Radio value={2}>测试</Radio>
                    </Radio.Group>

                </Col>
            </Row>
            <Row>
                <Col className="title_information" style={{marginTop: 20}}>商品图片</Col>
            </Row>
            <Row style={{marginTop: 20, marginBottom: 20}}>
                <Col span="3" offset="2" className="text_align_center">
                    <Row justify='center' className='imgTitle'>
                        <span>首页大图</span>
                    </Row>
                    <Upload
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        beforeUpload={beforeUpload}
                        onChange={this.handleChange(1)}
                    >
                        {imageUrlOne ? <img src={imageUrlOne} alt="avatar" style={{width: '100%'}}/> : uploadButton}
                    </Upload>

                </Col>
                <Col span={4} offset={2}>
                    <Row justify='center' className='imgTitle'>
                        <span>详情页大图</span>
                    </Row>

                    <Upload
                        name="avatar"
                        listType="picture-card"
                        className="avatar-uploader"
                        showUploadList={false}
                        action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                        beforeUpload={beforeUpload}
                        onChange={this.handleChange(2)}
                    >
                        {imageUrlTwo ? <img src={imageUrlTwo} alt="avatar" style={{width: '100%'}}/> : uploadButton}
                    </Upload>
                </Col>

            </Row>
            <Row>
                <Col span="3" offset="2" className='imgTitle'>
                    <span>正文大图</span>
                </Col>
            </Row>
            <Row>
                <Col span="22" offset="2">
                    <Row justify='left'>
                        <Upload
                            action="https://www.mocky.io/v2/5cc8019d300000980a055e76"
                            listType="picture-card"
                            fileList={fileList}
                            onPreview={this.handlePreview}
                            onChange={this.handleMoreChange}
                        >
                            {fileList.length >= 6 ? null : uploadButton}
                        </Upload>
                        <Modal
                            style={{width: 148, height: 148, marginLeft: 40}}
                            visible={previewVisible}
                            title={previewTitle}
                            footer={null}
                            onCancel={this.handleCancel}
                        >
                            <img alt="example" style={{width: '100%'}} src={previewImage}/>
                        </Modal>
                    </Row>


                </Col>


            </Row>
            <Row style={{marginTop: 20}}>
                <Col className="title_information">商品规格</Col>
            </Row>
            <Table bordered pagination={false} columns={columns} dataSource={tableData}/>
            <Row className="text_align_center" style={{margin: 20}}>
                <Col span={12} style={{paddingRight: 20}} align='right'>
                    <Button type='primary' className='btStyle'>
                        发布
                    </Button>
                </Col>
                <Col span={12} style={{paddingLeft: 20}}>
                    <Button type='primary' className='btStyle'>
                        取消
                    </Button>
                </Col>


            </Row>
        </div>)
    }
}

export default AddGoods                  //公开组件